﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Web;

namespace TNCAddIn
{
    class HttpClient
    {
        //获取成本中心
        public void GetBugetCenter()
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            try
            {
                Properties.Settings.Default.Centers = System.Text.Encoding.UTF8.GetString(wc.DownloadData(Properties.Settings.Default.ServerBaseUrl+Properties.Settings.Default.CenterUrl));
                string centers = Properties.Settings.Default.Centers;
                if (!centers.Contains("私人事件")) {
                    centers += ",私人事件";
                    Properties.Settings.Default.Centers = centers;
                }
                Properties.Settings.Default.Save();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //需要认证的POST接口
        public void AuthedPost(String mail, String data)
        {
            Encrypt enc = new Encrypt();
            data = enc.Encode(data);
            try
            {
                byte[] bs = UTF8Encoding.UTF8.GetBytes("email=" + mail + "&data=" + System.Web.HttpUtility.UrlEncode(data));
                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(Properties.Settings.Default.ServerBaseUrl + Properties.Settings.Default.DServer);
                myReq.Method = "POST";
                myReq.ContentType = "application/x-www-form-urlencoded";
                myReq.ContentLength = bs.Length;
                Stream reqStream = myReq.GetRequestStream();
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();

                HttpWebResponse myRes = (HttpWebResponse)myReq.GetResponse();
                Stream resStream = myRes.GetResponseStream();

                StreamReader sr = new StreamReader(resStream, UTF8Encoding.UTF8);
                String res = sr.ReadToEnd();

                resStream.Close();

                int index = res.IndexOf("1");

                if (index != 0)
                {
                    throw new Exception(res);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        //需要认证的下载
        public void AuthDownload(String mail, String data, String path, Boolean showProcess) 
        {
            Encrypt enc = new Encrypt();
            data = enc.Encode(data);
            String param = "email=" + mail + "&data=" + data;
            WaitingForm wf = new WaitingForm();
            if(showProcess)
                wf.Show();
            try
            {
                wf.Text = "正在建立连接……";
                byte[] bs = UTF8Encoding.UTF8.GetBytes(param);
                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(Properties.Settings.Default.ServerBaseUrl + Properties.Settings.Default.Download);
                myReq.Method = "POST";
                myReq.ContentType = "application/x-www-form-urlencoded";
                myReq.ContentLength = bs.Length;
                Stream reqStream = myReq.GetRequestStream();
                wf.Text = "正在进行验证……";
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();

                HttpWebResponse myRes = (HttpWebResponse)myReq.GetResponse();
                Stream resStream = myRes.GetResponseStream();
                FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);

                wf.Text = "正在下载结果……";
                int i = 0;
                decimal j = 0;

                byte[] buffer = new byte[1024];
                while (true)
                {
                    i = resStream.Read(buffer, 0, buffer.Length);
                    if (i == 0)
                        break;
                    else
                        fs.Write(buffer, 0, i);
                    j += i;

                }

                resStream.Close();
                fs.Close();
                wf.Close();
                if(j < 8) 
                {
                    throw new Exception("验证失败，请检查邮箱及密码！");
                }
            }
            catch (Exception e)
            {
                wf.Close();
                throw e;
            }
        }

        //需要认证的上传
        public void AuthUpload(String mail, String data, String paths)
        {
            try
            {
                Encrypt enc = new Encrypt();
                data = enc.Encode(data);

                string boundary = "----------------------------" +
                DateTime.Now.Ticks.ToString("x");

                String authStr = enc.Encode(DateTime.Now.ToString());
                String test = System.Web.HttpUtility.UrlEncode(authStr);

                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(Properties.Settings.Default.ServerBaseUrl + Properties.Settings.Default.Server + "?email=" + mail + "&data=" + test);
                myReq.ContentType = "multipart/form-data; boundary=" + boundary;
                myReq.Method = "POST";
                myReq.KeepAlive = true;
                //myReq.Credentials = 

                Stream memStream = new MemoryStream();
                byte[] boundarybytes = UTF8Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");

                String formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

                String formMail = String.Format(formdataTemplate, "email", mail);
                byte[] formMailBytes = UTF8Encoding.UTF8.GetBytes(formMail);
                memStream.Write(formMailBytes, 0, formMailBytes.Length);

                String formData = String.Format(formdataTemplate, "data", data);
                byte[] formDataBytes = UTF8Encoding.UTF8.GetBytes(formData);
                memStream.Write(formDataBytes, 0, formDataBytes.Length);

                memStream.Write(boundarybytes, 0, boundarybytes.Length);

                if (paths != "")
                {
                    String headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";


                    String[] pathArray = paths.Split(',');

                    for (int i = 0; i < pathArray.Length; i++)
                    {

                        //string header = string.Format(headerTemplate, "file" + i, files[i]);
                        String header = String.Format(headerTemplate, "uplTheFile", pathArray[i]);

                        byte[] headerbytes = UTF8Encoding.UTF8.GetBytes(header);

                        memStream.Write(headerbytes, 0, headerbytes.Length);


                        FileStream fileStream = new FileStream(pathArray[i], FileMode.Open, FileAccess.Read);
                        byte[] buffer = new byte[1024];

                        int bytesRead = 0;

                        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            memStream.Write(buffer, 0, bytesRead);

                        }

                        memStream.Write(boundarybytes, 0, boundarybytes.Length);

                        fileStream.Close();
                    }
                }

                myReq.ContentLength = memStream.Length;

                Stream requestStream = myReq.GetRequestStream();

                memStream.Position = 0;
                byte[] tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();

                HttpWebResponse myRes = (HttpWebResponse)myReq.GetResponse();
                Stream resStream = myRes.GetResponseStream();

                StreamReader sr = new StreamReader(resStream, UTF8Encoding.UTF8);
                String res = sr.ReadToEnd();

                resStream.Close();

                int index = res.IndexOf("1");

                if (index != 0)
                {
                    throw new Exception(res);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}
